#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "light_control.h"

lightconn * light_init()
{
        int sock;
        struct sockaddr_in localAddr;
        lightconn * l = (lightconn *)malloc(sizeof(lightconn));

        if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
                fprintf(stderr, "Error getting socket.\n");
                return NULL;
        }

        memset(&localAddr, 0, sizeof(localAddr));
        localAddr.sin_family = AF_INET;
        localAddr.sin_addr.s_addr = inet_addr(SERVERIP);
        localAddr.sin_port = htons(PORT);

        if (connect(sock, (struct sockaddr *) &localAddr, sizeof(localAddr)) < 0) {
                fprintf(stderr, "Connect failed!\n");
                return NULL;
        }

        l->sock = sock;
        l->connected = 1;
        l->status = 1;
        lightoff(l, 0);

        return l;
}


void light_destroy(lightconn * c)
{
        if (c->connected)
                close(c->sock);
        free(c);
}

void s() {
        int i;
        for (i = 0; i < 6000; i++) ;
}

void lighton(lightconn * c, int d)
{
        if (d == 0 && c->status == 1)
                return;
        send(c->sock, "\355", 1, 0);
        send(c->sock, "\"", 1, 0);
        send(c->sock, "\3", 1, 0);
        send(c->sock, "\10\0\1", 3, 0);
        send(c->sock, "\25", 1, 0);
        send(c->sock, "\355", 1, 0);
        send(c->sock, "#", 1, 0);
        send(c->sock, "\3", 1, 0);
        send(c->sock, "\t\0\1", 3, 0);
        send(c->sock, "%", 1, 0);
        if (!d) {
                s();
                lighton(c, 1);
        }
        c->status = 1;
}

void lightoff(lightconn * c, int d)
{
        if (d == 0 && c->status == 0)
                return;

        send(c->sock, "\355", 1, 0);
        send(c->sock, "\22", 1, 0);
        send(c->sock, "\3", 1, 0);
        send(c->sock, "\10\0\1", 3, 0);
        send(c->sock, "\30", 1, 0);
        send(c->sock, "\355", 1, 0);
        send(c->sock, "\23", 1, 0);
        send(c->sock, "\3", 1, 0);
        send(c->sock, "\t\0\0", 3, 0);
        send(c->sock, "+", 1, 0);
        if (!d) {
                s();
                lightoff(c, 1);
        }
        c->status = 0;
}

#ifdef LCTEST
int main(int argc, char **argv)
{
        lightconn * c = light_init();

        if (argc < 2 || strcmp(argv[1], "on") == 0) {
                lighton(c, 0);
        }
        else {
                lightoff(c, 0);
        }
        light_destroy(c);
        return 0;
}
#endif
